package cn.com.thingo.hyintelligent.ui.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.videogo.device.DeviceInfo;
import com.videogo.errorlayer.ErrorInfo;
import com.videogo.exception.BaseException;
import com.videogo.exception.ErrorCode;
import com.videogo.openapi.EZOpenSDK;
import com.videogo.openapi.bean.EZDeviceInfo;
import com.videogo.openapi.bean.EZUserInfo;
import com.videogo.util.ConnectionDetector;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.com.thingo.hyintelligent.R;
import cn.com.thingo.hyintelligent.app.EzHttpConstants;
import cn.com.thingo.hyintelligent.base.BaseActivity;
import cn.com.thingo.hyintelligent.base.contract.EzDeviceManageContract;
import cn.com.thingo.hyintelligent.model.bean.BaseBean;
import cn.com.thingo.hyintelligent.model.bean.EzAddDevicePermissionBean;
import cn.com.thingo.hyintelligent.model.bean.EzDeviceAuthorizationListBean;
import cn.com.thingo.hyintelligent.model.bean.PermissionJsonBean;
import cn.com.thingo.hyintelligent.model.db.UserInfo;
import cn.com.thingo.hyintelligent.presenter.EzDeviceManagerPresenter;
import cn.com.thingo.hyintelligent.ui.adapter.EzDeviceManagerListAdapter;
import cn.com.thingo.hyintelligent.util.ActivityUtils;
import cn.com.thingo.hyintelligent.util.GsonUtil;
import cn.com.thingo.hyintelligent.util.LogUtil;
import cn.com.thingo.hyintelligent.util.NumberVerifiedUtils;
import cn.com.thingo.hyintelligent.util.ToastUtil;
import cn.com.thingo.hyintelligent.util.WaitDialogUtils;
import cn.com.thingo.hyintelligent.widget.WaitDialog;

public class EzDeviceManagerActivity extends BaseActivity<EzDeviceManagerPresenter> implements EzDeviceManageContract.View {
    @BindView(R.id.toolbar_left)
    ImageView ivLeft;
    @BindView(R.id.toolbar_title)
    TextView tvTitle;
    @BindView(R.id.toolbar_right)
    ImageView ivRight;
    @BindView(R.id.rv_manager)
    RecyclerView rvManager;
    private UserInfo mUserInfo;
    private EzDeviceManagerListAdapter mAdapter;
    private List<EZDeviceInfo> mEzDeviceInfos;
    private AlertDialog alertDialog;
    private String deviceSerial;
    public static final String DELETE_DEVICE_SUCCESS_ACTION = "DELETE_DEVICE_SUCCESS_ACTION";
    private WaitDialog mWaitDialog;

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_ezdevice_manager;
    }

    @Override
    protected void initEventAndData() throws Exception {
        mUserInfo = UserInfo.getInstance();
        ivLeft.setImageResource(R.mipmap.back);
        tvTitle.setText(R.string.monitor_manager);
        initView();
    }

    private void initView() {

        mEzDeviceInfos = new ArrayList<>();
        mAdapter = new EzDeviceManagerListAdapter(mEzDeviceInfos);
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        rvManager.setLayoutManager(manager);
        rvManager.setAdapter(mAdapter);
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(final BaseQuickAdapter adapter, View view, final int position) {
                deviceSerial = ((EZDeviceInfo) adapter.getData().get(position)).getDeviceSerial();
                switch (view.getId()) {
                    case R.id.tv_delete:
                        new AlertDialog.Builder(mContext, AlertDialog.THEME_HOLO_LIGHT).setTitle("删除设备").setNegativeButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                              mWaitDialog = WaitDialogUtils.showWaitDialog(mContext);
                                mPresenter.delEzDevicePermission(mUserInfo.getAccessToken(), mUserInfo.getUserName(), mUserInfo.getUserName(), deviceSerial);

                            }
                        }).setNeutralButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        }).show();
                        break;
                    case R.id.tv_auth:

                        View dialogView = LayoutInflater.from(mContext).inflate(R.layout.dialog_add_auth, null);
                        final EditText etTelephone = dialogView.findViewById(R.id.dialog_add_auth_input);
                        TextView tvDetermine = dialogView.findViewById(R.id.dialog_add_auth_determine);
                        TextView tvCancel = dialogView.findViewById(R.id.dialog_add_auth_cancel);
                        alertDialog = new AlertDialog.Builder(mContext, AlertDialog.THEME_HOLO_LIGHT).setView(dialogView).create();
                        tvDetermine.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                String telephone = etTelephone.getText().toString();
                                if (!NumberVerifiedUtils.isTelephone(telephone)) {
                                    ToastUtil.show("号码格式错误");
                                } else if (telephone.equals(mUserInfo.getUserName())) {
                                    ToastUtil.show("不能授权给自己");
                                } else {
                                    PermissionJsonBean bean = new PermissionJsonBean();
                                    bean.setPermission("Get,DevCtrl");
                                    List<String> list = new ArrayList<>();
                                    list.add("dev:" + deviceSerial);
                                    bean.setResource(list);
                                    String jsonStr = GsonUtil.GsonString(bean);
                                    mWaitDialog = WaitDialogUtils.showWaitDialog(mContext);
                                    mPresenter.addEzDevicePermission(mUserInfo.getAccessToken(), mUserInfo.getUserName(), telephone, jsonStr);
                                }
                            }
                        });
                        tvCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                alertDialog.dismiss();
                            }
                        });
                        alertDialog.show();
                        break;
                }
            }
        });
        mPresenter.getDeviceInfoList();
    }


    /**
     * 删除设备任务
     */
    private class DeleteDeviceTask extends AsyncTask<Void, Void, Boolean> {

        private Dialog mWaitDialog;

        private int mErrorCode = 0;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            EZOpenSDK.getInstance().setAccessToken(mUserInfo.getAccessToken());
            mWaitDialog = new WaitDialog(EzDeviceManagerActivity.this, android.R.style.Theme_Translucent_NoTitleBar);
            mWaitDialog.setCancelable(false);
            mWaitDialog.show();
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            if (!ConnectionDetector.isNetworkAvailable(EzDeviceManagerActivity.this)) {
                mErrorCode = ErrorCode.ERROR_WEB_NET_EXCEPTION;
                return false;
            }

            try {
//            	EZCameraInfo cameraInfo = params[0];
                EZOpenSDK.getInstance().deleteDevice(deviceSerial);
                return true;
            } catch (BaseException e) {
                ErrorInfo errorInfo = (ErrorInfo) e.getObject();
                mErrorCode = errorInfo.errorCode;
                LogUtil.e(errorInfo.toString());

                return false;
            }
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            EZOpenSDK.getInstance().setAccessToken(mUserInfo.getRamAccessToken());
            Intent intent = new Intent(DELETE_DEVICE_SUCCESS_ACTION);
            sendBroadcast(intent);
            mWaitDialog.dismiss();
            if (result) {
                mPresenter.getDeviceInfoList();
            } else {
                switch (mErrorCode) {
                    case ErrorCode.ERROR_WEB_SESSION_ERROR:
                        ActivityUtils.handleSessionException(EzDeviceManagerActivity.this);
                        break;
                    case ErrorCode.ERROR_WEB_HARDWARE_SIGNATURE_ERROR:
                        ActivityUtils.handleSessionException(EzDeviceManagerActivity.this);
                        break;
                    case ErrorCode.ERROR_WEB_NET_EXCEPTION:
                        ToastUtil.show(R.string.alarm_message_del_fail_network_exception);
                        break;
                    case ErrorCode.ERROR_WEB_DEVICE_VALICATECODE_ERROR:
                        ToastUtil.show(R.string.verify_code_error);
                    default:
                        ToastUtil.show("删除失败,未知错误");
                        break;
                }
            }
        }
    }


    @Override
    public void showDeviceInfoList(List<EZDeviceInfo> list) {
        mEzDeviceInfos = list;
        if (list != null) {
            mPresenter.getEzDeviceList(mUserInfo.getAccessToken(), mUserInfo.getUserName(), mUserInfo.getUserName());
        }

    }

    @Override
    public void viewAddEzDevicePermissionResult(BaseBean bean) {
        if (mWaitDialog != null) {
            WaitDialogUtils.dismissWaitDialog(mWaitDialog);
        }
        alertDialog.dismiss();
        ToastUtil.show(bean.getMsg());
    }

    @Override
    public void viewDelEzDevicePermissionResult(BaseBean bean) {
        if (mWaitDialog != null) {
            WaitDialogUtils.dismissWaitDialog(mWaitDialog);
        }
        if (bean.getStatus() == 1) {
            new DeleteDeviceTask().execute();
            ToastUtil.show("删除成功");
        }
        ToastUtil.show(bean.getMsg());
    }

    @Override
    public void viewEzDeviceListResult(BaseBean<List<EzDeviceAuthorizationListBean>> bean) {
        if (bean.getStatus() == 1) {
            mAdapter.setNewData(null);
            List<EzDeviceAuthorizationListBean> data = bean.getData();
            for (EzDeviceAuthorizationListBean listBean : data
            ) {
                String deviceSerial = listBean.getDev_sn();
                for (EZDeviceInfo dev :
                        mEzDeviceInfos) {
                    if (deviceSerial.equals(dev.getDeviceSerial())) {
                        mAdapter.addData(dev);
                        break;
                    }
                }
            }

        }
    }


    @OnClick({R.id.toolbar_left})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.toolbar_left:
                finish();
                break;
        }
    }
}
